<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="需求计划编号" prop="mrpCode">
          <el-input
            v-model="queryParams.mrpCode"
            placeholder="请输入物料需求计划编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="需求计划名称" prop="mrpName">
          <el-input
            v-model="queryParams.mrpName"
            placeholder="请输入物料需求计划名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>


    <el-card style="border-radius: 10px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['mrp:mrp:add']"
          >新增</el-button>
        </el-col>
        <!--      <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-edit"
                  size="mini"
                  :disabled="single"
                  @click="handleUpdate"
                  v-hasPermi="['mrp:mrp:edit']"
                >修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                  v-hasPermi="['mrp:mrp:remove']"
                >删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExport"
                  v-hasPermi="['mrp:mrp:export']"
                >导出</el-button>
              </el-col>-->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="mrpList" @selection-change="handleSelectionChange" border>
        <!--      <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column label="物料需求计划编号" align="center" prop="mrpCode" />
        <el-table-column label="物料需求计划名称" align="center" prop="mrpName" />
        <el-table-column label="需求来源" align="center" prop="requirementSource" />
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === '已完成'" type="success">已完成</el-tag>
            <el-tag v-if="scope.row.status === '草稿'" type="info">草稿</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createBy" />
        <el-table-column label="创建时间" align="center" prop="createTime"></el-table-column>
        <el-table-column label="修改人" align="center" prop="updateBy" />
        <el-table-column label="修改时间" align="center" prop="updateTime"></el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
              v-hasPermi="['mrp:mrp:query']"
              v-if="scope.row.status === '已完成'"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['mrp:mrp:edit']"
              v-if="scope.row.status === '草稿'"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['mrp:mrp:remove']"
              v-if="scope.row.status === '草稿'"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>


    <!-- 添加或修改物料需求计划（MRP）对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1350px" append-to-body>
      <el-card style="border-radius: 10px">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="计划编号" prop="mrpCode">
                <el-input v-model="form.mrpCode" placeholder="请输入物料需求计划编号" :readonly="optType !== 'add'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划名称" prop="mrpName">
                <el-input v-model="form.mrpName" placeholder="请输入物料需求计划名称" :readonly="optType === 'view'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="需求来源" prop="requirementSource">
                <el-select v-model="form.requirementSource" placeholder="请选择需求来源">
                  <el-option label="销售预测计划" value="销售预测计划" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计算规则" prop="computationRule">
                <el-checkbox
                  v-model="form.computationRule"
                  true-label="Y"
                  false-label="N"
                  :disabled="optType === 'view'"
                >可用库存数量</el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="this.form.computationRule === 'Y'">
            <el-col :span="12">
              <el-form-item label="仓库" prop="warehouseId">
                <el-select
                  v-model="warehouseInfo"
                  multiple
                  value-key="warehouseId"
                  :disabled="optType === 'view'"
                  placeholder="请选择仓库">
                  <el-option
                    v-for="item in warehouseList"
                    :key="item.warehouseId"
                    :label="item.warehouseName"
                    :value="item">
                    {{item.warehouseName}}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- MRP产品 -->
          <MrpLine
              ref="mrpLine"
              :mrpId="form.id"
              :optType="optType"
              :computationRule="form.computationRule"
              v-if="form.id !== null"
          ></MrpLine>

        </el-form>
      </el-card>


      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="handleConfirm" v-if="optType === 'update'">提 交</el-button>
        <el-button type="primary" @click="submitForm" v-if="optType !== 'view'">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 加载提示 -->
    <el-dialog
        :visible.sync="loadingTips"
        width="30%"
        :modal="true"
        :show-close="false"
        :close-on-click-modal="false"
        custom-class="mrp-loading-dialog"
    >
    <div class="loading-content">
      <div class="loading-spinner">
        <i class="el-icon-loading"></i>
      </div>
      <p>MRP运算中，请稍等...</p>
    </div>
    </el-dialog>

    <!-- 详情页面 -->
    <el-dialog :title="viewTitle" :visible.sync="viewOpen" width="80%" append-to-body>
      <el-card style="border-radius: 10px">
        <el-form ref="form" :model="form" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="计划编号" prop="mrpCode">
                <el-input v-model="form.mrpCode" placeholder="请输入物料需求计划编号" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划名称" prop="mrpName">
                <el-input v-model="form.mrpName" placeholder="请输入物料需求计划名称" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="需求来源" prop="requirementSource">
                <el-input v-model="form.requirementSource" placeholder="请输入需求来源" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计算规则" prop="computationRule">
                <el-checkbox
                  v-model="form.computationRule"
                  true-label="Y"
                  false-label="N"
                  disabled
                >可用库存数量</el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="form.computationRule === 'Y'">
            <el-col :span="12">
              <el-form-item label="仓库" prop="warehouseId">
                <el-select
                  v-model="warehouseInfo"
                  multiple
                  value-key="warehouseId"
                  disabled
                  placeholder="请选择仓库">
                  <el-option
                    v-for="item in warehouseList"
                    :key="item.warehouseId"
                    :label="item.warehouseName"
                    :value="item">
                    {{item.warehouseName}}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- tab页面 -->
        <el-row>
          <div class="mod-config" style="width: 100%;">
            <el-tabs v-model="tabValue" type="card" @tab-click="handleTabClick">
              <el-tab-pane v-for="item in dicList" :key="item.value" :label="item.label" :name="item.value">
              </el-tab-pane>
            </el-tabs>

            <!-- 产品信息 -->
            <div v-show="isItem">
              <el-table :data="mrpLineList" style="margin-top: 20px;" border>
                <el-table-column label="产品编号" align="center" prop="itemCode" />
                <el-table-column label="产品名称" align="center" prop="itemName" />
                <el-table-column label="规格型号" align="center" prop="specification" />
                <el-table-column label="单位" align="center" prop="unitOfMeasure" />
                <el-table-column label="计划数量" align="center" prop="quantity" />
                <el-table-column
                  label="可用库存数量"
                  align="center"
                  prop="availableInventoryQuantity"
                  v-if="this.form.computationRule === 'Y'"
                />
                <el-table-column label="需求数量" align="center" prop="requiredQuantity" />
                <el-table-column label="BOM版本" align="center" prop="bomName" />
              </el-table>
              <pagination
                v-show="lineTotal>0"
                :total="lineTotal"
                :page.sync="lineQueryParams.pageNum"
                :limit.sync="lineQueryParams.pageSize"
                @pagination="getLineList"
              />
            </div>

            <!-- 采购计划 -->
            <div v-show="isPurchase">
              <el-row>
                <el-button type="primary" @click="addPurchasePlan" v-if="form.purchasePlanCode === null">生成采购计划</el-button>
                <div class="purchase-info-container" v-if="form.purchasePlanCode !== null">
                  <span class="purchase-info-item">采购计划编号：&nbsp;{{form.purchasePlanCode}}&nbsp;&nbsp;</span>
                  <span class="purchase-info-item">采购计划日期：&nbsp;{{form.purchasePlanDate}}&nbsp;&nbsp;</span>
                  <span class="purchase-info-item">物料需求截止日期：&nbsp;{{form.materialDeadline}}&nbsp;&nbsp;</span>
                </div>
              </el-row>
              <el-row>
                <el-table :data="mrpItemList" style="margin-top: 20px;" border>
                  <el-table-column label="物料编号" align="center" prop="itemCode" />
                  <el-table-column label="物料名称" align="center" prop="itemName" />
                  <el-table-column label="规格型号" align="center" prop="specification" />
                  <el-table-column label="单位" align="center" prop="unitOfMeasure" />
                  <el-table-column label="理论需求数量" align="center" prop="theoryRequiredQuantity" />
                  <el-table-column
                    label="可用库存数量"
                    align="center"
                    prop="availableInventoryQuantity"
                    v-if="form.computationRule === 'Y'"
                  />
                  <el-table-column label="需求数量" align="center" prop="requiredQuantity" />
                </el-table>
                <pagination
                  v-show="itemTotal>0"
                  :total="itemTotal"
                  :page.sync="itemQueryParams.pageNum"
                  :limit.sync="itemQueryParams.pageSize"
                  @pagination="getItemList"
                />
              </el-row>
            </div>

          </div>
        </el-row>



      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleTabCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 采购计划新增 -->
    <AddPurchase ref="addPurchase" ></AddPurchase>



  </div>
</template>

<script>
import { listMrp, getMrp, delMrp, addMrp, updateMrp, submitMrp } from "@/api/mes/mrp/promrp";
import { genCode } from "@/api/system/autocode/rule";
import { getWarehouseList } from "@/api/mes/wm/warehouse";
import MrpLine from "./line.vue";
import { listMrpLine } from "@/api/mes/mrp/mrpLine";
import { listMrpItem, listMrpItemAll } from "@/api/mes/mrp/mrpItem";
import AddPurchase from "./addPurchase.vue";

export default {
  name: "ProMrp",
  components: { MrpLine, AddPurchase },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料需求计划（MRP）表格数据
      mrpList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mrpCode: null,
        mrpName: null,
        requirementSource: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        computationRule: null,
        status: null,
        purchasePlanId: null,
        purchasePlanCode: null,
        purchasePlanDate: null,
        materialDeadline: null,
        outsourcingPlanId: null,
        outsourcingPlanCode: null,
        deadline: null,
        proPlanId: null,
        proPlanCode: null,
        requestDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        mrpCode: [
          { required: true, message: "物料需求计划编号不能为空", trigger: "blur" }
        ],
        requirementSource: [
          { required: true, message: "需求来源不能为空", trigger: "change" }
        ],
        warehouseInfo: [
          { required: true, message: "仓库不能为空", trigger: "change" }
        ],
      },
      // 显隐开关
      optType: null,
      // 仓库列表
      warehouseList: [],
      // 仓库信息
      warehouseInfo:[],
      // 加载提示
      loadingTips: false,
      // 详情标题
      viewTitle: "",
      // 详情开关
      viewOpen: false,
      // tab默认选项
      tabValue: '0',
      // tab标签组
      dicList: [
        { label: "产品信息", value: '0' },
        { label: "采购计划", value: '1' },
      ],
      // 物料需求计划（MRP）产品表格数据
      mrpLineList: [],
      // 产品信息开关
      isItem: false,
      // 产品信息查询参数
      lineQueryParams: {
        pageNum: 1,
        pageSize: 10,
        mrpId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        quantity: null,
        availableInventoryQuantity: null,
        requiredQuantity: null,
        bomId: null,
        bomCode: null,
        bomName: null,
      },
      // 产品总条数
      lineTotal: 0,
      // 采购计划需求物料表格数据
      mrpItemList: [],
      // 采购开关
      isPurchase: false,
      // 采购计划需求物料查询参数
      itemQueryParams: {
        pageNum: 1,
        pageSize: 10,
        mrpId: null,
        itemCode: null,
        itemName: null,
        specification: null,
        unitOfMeasure: null,
        itemType: null,
        theoryRequiredQuantity: null,
        availableInventoryQuantity: null,
        requiredQuantity: null,
      },
      // 采购计划需求物料总条数
      itemTotal: 0,
      // 不分页物料集合
      mrpItemListAll: [],

    };
  },
  created() {
    this.getList();
    this.getWarehouseList();
  },
  methods: {
    /** 查询物料需求计划（MRP）列表 */
    getList() {
      this.loading = true;
      listMrp(this.queryParams).then(response => {
        this.mrpList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        mrpCode: null,
        mrpName: null,
        requirementSource: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        computationRule: null,
        status: "草稿",
        purchasePlanId: null,
        purchasePlanCode: null,
        purchasePlanDate: null,
        materialDeadline: null,
        outsourcingPlanId: null,
        outsourcingPlanCode: null,
        deadline: null,
        proPlanId: null,
        proPlanCode: null,
        requestDate: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.warehouseInfo = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      genCode('MRP_CODE').then(response =>{
        this.form.mrpCode = response;
      });
      this.open = true;
      this.title = "添加物料需求计划（MRP）";
      this.optType = "add";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMrp(id).then(response => {
        this.form = response.data;
        this.warehouseInfo = this.getWarehouseInfoByIds(this.form.warehouseId);
        this.open = true;
        this.title = "修改物料需求计划（MRP）";
        this.optType = "update";
      });
    },
    /** 保存按钮操作 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 转换选中的仓库信息为字符串
          const ids = this.warehouseInfo.map(item => item.warehouseId).join(',');
          const codes = this.warehouseInfo.map(item => item.warehouseCode).join(',');
          const names = this.warehouseInfo.map(item => item.warehouseName).join(',');

          this.form.warehouseId = ids;
          this.form.warehouseCode = codes;
          this.form.warehouseName = names;
          if (this.form.id != null) {
            updateMrp(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMrp(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物料需求计划（MRP）编号为"' + row.mrpCode + '"的数据项？').then(function() {
        return delMrp(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mrp/mrp/export', {
        ...this.queryParams
      }, `mrp_${new Date().getTime()}.xlsx`)
    },
    /** 提交按钮操作 */
    async handleConfirm() {
      // 关闭弹窗
      this.open = false;
      // 打开运算提示
      this.loadingTips = true;

      try {
        this.form.status = '已完成';
        const response = await submitMrp(this.form);
        // 10秒后关闭提示
        setTimeout(() => {
          this.loadingTips = false;
          if (response.code === 200) {
            this.$modal.msgSuccess("提交成功");
            this.getList();
          }else {
            this.$modal.msgError("提交失败")
          }
        }, 10000);
      } catch (error) {
        console.error("提交失败：", error);
        this.loadingTips = false;
        this.$modal.msgError("提交失败");
      }

    },
    /** 获取仓库下拉列表 */
    getWarehouseList() {
      getWarehouseList().then(response => {
        this.warehouseList = response.data
      })
    },
    /** 根据 warehouseId 字符串还原对象数组 */
    getWarehouseInfoByIds(idStr) {
      if (!idStr) return [];
      const idArray = idStr.split(',').map(id => id.trim());
      return this.warehouseList.filter(item =>
        idArray.includes(item.warehouseId.toString())
      );
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids
      getMrp(id).then(response => {
        this.form = response.data;
        this.warehouseInfo = this.getWarehouseInfoByIds(this.form.warehouseId);
        this.viewOpen = true;
        this.viewTitle = "查看物料需求计划（MRP）";
        this.optType = "view";
        this.tabValue = "0";
        this.isItem = true;
        this.isPurchase = false;
        this.lineQueryParams.pageNum = 1;
        this.itemQueryParams.pageNum = 1;
        this.getLineList();
      });
    },
    /** 获取产品信息列表 **/
    getLineList() {
      this.mrpLineList = [];
      this.lineQueryParams.mrpId = this.form.id;
      listMrpLine(this.lineQueryParams).then(response => {
        this.mrpLineList = response.rows;
        this.lineTotal = response.total;
      });
    },
    /** 获取采购需求物料信息列表 **/
    getItemList() {
      this.mrpItemList = [];
      this.itemQueryParams.mrpId = this.form.id;
      listMrpItem(this.itemQueryParams).then(response => {
        this.mrpItemList = response.rows;
        this.itemTotal = response.total;
      });
    },
    // 查看页面取消按钮
    handleTabCancel() {
      this.viewOpen = false;
      this.tabValue = '0';
    },
    /** tab点击 **/
    handleTabClick(tab, event) {
      if (tab.name === '0') {
        this.tabValue = tab.name;
        this.isItem = true;
        this.isPurchase = false;
        this.lineQueryParams.pageNum = 1;
        this.getLineList();
      }else if (tab.name === '1') {
        this.tabValue = tab.name;
        this.isItem = false;
        this.isPurchase = true;
        this.itemQueryParams.pageNum = 1;
        this.getItemList();
      }
    },
    /** 生成采购计划 **/
    async addPurchasePlan() {
      await this.getMrpItemListAll();
      this.$refs.addPurchase.open = true;
      this.$refs.addPurchase.autoGenFlag = false;
      this.$refs.addPurchase.title = '新增采购计划';
      this.$refs.addPurchase.optType = 'add';
      let list = [];
      if (this.form.computationRule === 'Y') {
        list = this.mrpItemListAll.filter(item => item.requiredQuantity > 0);
      }else if (this.form.computationRule === 'N') {
        list = this.mrpItemListAll;
      }
      if (this.$refs.addPurchase) {
        this.$refs.addPurchase.addGoodsList = list.map(item => ({
          itemId: item.itemId,
          itemCode: item.itemCode,
          itemName: item.itemName,
          specification: item.specification,
          unitOfMeasure: item.unitOfMeasure,
          quantity: item.requiredQuantity,
        }));
      }else {
        this.$refs.addPurchase.addGoodsList = [];
      }
      this.$refs.addPurchase.init();
      this.$refs.addPurchase.form.sourceDocId = this.form.id;
      this.$refs.addPurchase.form.sourceDocType = 'MRP';

    },
    // 获取不分页的采购需求物料信息列表
    async getMrpItemListAll() {
      this.mrpItemListAll = [];
      this.itemQueryParams.mrpId = this.form.id;
      const response = await listMrpItemAll(this.itemQueryParams);
      this.mrpItemListAll = response.data;
    },

  }
};
</script>

<style scoped>.app-container {
  padding: 20px;
}

.mrp-loading-dialog .loading-content {
  text-align: center;
}

.mrp-loading-dialog .loading-spinner {
  font-size: 50px;
  color: #409EFF;
  margin-bottom: 10px;
}

.purchase-info-container {
  display: inline-flex;
  gap: 150px;
  margin-left: 100px;
  margin-top: 15px;
}

.purchase-info-item {
  white-space: nowrap;
}

</style>
